﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace RFCReader
{
    static class Program
    {
        private delegate void ExceptionDelegate(Exception x);
        static private MainForm _MainForm;
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            ShowErrReportDlg(e.Exception);
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string [] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
                if (args.Length > 0)
                {
                    _MainForm = new MainForm(args[0]);

                }
                else
                {
                    _MainForm = new MainForm();

                }
                Application.Run(_MainForm);
            }
            catch (Exception e)
            {
                ShowErrReportDlg(e);
                throw e;
            }
           
            
        }

        private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {  
            Exception exception;  
            exception = e.ExceptionObject as Exception;  
            if (exception == null) { 
                // this is an unmanaged exception, you may want to handle it differently    
                return; 
            }  
            PublishOnMainThread(exception);
        }

        private static void PublishOnMainThread(Exception exception)
        {  
            if (_MainForm.InvokeRequired)  
            {    
                // Invoke executes a delegate on the thread that owns _MainForms's underlying window handle.    
                _MainForm.Invoke(new ExceptionDelegate(HandleException), new object[] {exception});  
            }  
            else  
            {    
                HandleException(exception);  
            }
        }
        public static void ShowErrReportDlg(Exception exception)
        {
            ErrReportForm f = new ErrReportForm();
            f.SetErrorInfo(exception.Message + "\r\n" + exception.StackTrace + "\r\n\r\n" + System.IO.File.ReadAllText(Config.CfgFile()));
            f.ShowDialog();
        }
        private static void HandleException(Exception e) 
        { 
            if (SystemInformation.UserInteractive) 
            {
                ShowErrReportDlg(e);
            } 
        }
    }
}